<?php
/**
 * Hello World default controller
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 * @license		GNU/GPL
 */

jimport('joomla.application.component.controller');
JTable::addIncludePath(JPATH_SITE.DS.'components'.DS.'com_servers'.DS.'tables');
JTable::addIncludePath(JPATH_SITE.DS.'components'.DS.'com_servers'.DS.'views');
/**
 * Hello World Component Controller
 *
 * @package		HelloWorld
 */
class ServersController extends JController {
/**
 * Method to display the view
 *
 * @access	public
 */
    function display() {
        parent::display();
    }
    
	function search() {
		 $post	= JRequest::get('post');
         $link = JRoute::_('index.php?option=com_servers&txt_search='.$post['txt_search']);
		 $this->setRedirect($link, $msg);
    }
    
	function get_coupon() {
		$db =& JFactory::getDBO();
		$get	= JRequest::get('get');
		$coupon_code = $get['code'];
         $query = ' SELECT value '
            . ' FROM #__a_coupons '
			. " WHERE coupon_code = '$coupon_code'"
          ;          
          $db->setQuery( $query);
          $coupon_value = $db->loadResult();
          print $coupon_value;exit;
    }
    
    function order(){
    	global $mainframe,$option;
    	include 'administrator/components/com_mwc_customer/tables/mwc_customer.php';
    	include 'administrator/components/com_mwc_order/tables/mwc_order.php';
    	include 'administrator/components/com_mwc_payment/tables/mwc_payment.php';
    	$db =& JFactory::getDBO();
    	
    	$obj_customer 	= new TableMwc_customer($db);
    	$obj_payment 	= new TableMwc_payment($db);
    	$obj_order 		= new TableMwc_order($db);
    	
    	$post	= JRequest::get('post');
    	$get	= JRequest::get('get');
    	
    	$query = ' SELECT max(id) '
            . ' FROM #__a_orders '

        ;
        $db->setQuery( $query);
        $order_id = $db->loadResult();
        $order_id = (int)$order_id + 1;
    	
    	//-- begin doing payment
    	require_once(JPATH_SITE."/components/com_servers/nusoap/nusoap.php");
    	$client = new  Soapclient('https://securesite.soeasypay.com/interface/payment2/index.php?wsdl');
        
    	$SaleTransactionRequest = array(

            'websiteID' => '102269',

            'password' => '0b9735673934d5b5b4210ce9be8f6ab6a22e695bbb75d1f68aaa32811637ff6b',

            'orderID' => '00',
            'customerIP' => $post['theip'],
            'amount' => ($post['total_price']-$post['coupon_value'])*100,
            'orderAmount' => "1",
            'currency' => "USD",
            'cardHolderName' => 'dd',
            'cardHolderAddress' => 'd',
            'cardHolderZipcode' => 'd',
            'cardHolderCity' => 'd',
            'cardHolderState' => 'd',
            'cardHolderCountryCode' => 'd',
            'cardHolderPhone' => 'NA',
            'cardHolderEmail' => $post['email'],
            'cardNumber' => $post['credit_card_number'],
            'cardSecurityCode' => $post['card_security_code'],
            'cardExpireMonth' => $post['exp_month'],
            'cardExpireYear' => $post['exp_year'],
            'AVSPolicy' => "",
            'FSPolicy' => "",
            'Secure3DAcsMessage' => "",

            'userVar1' => "v",

            'userVar2' => "v",

            'userVar3' => "v",

            'userVar4' => "v"	);
        $result = $client->SaleTransaction($SaleTransactionRequest);
        //echo "<pre>";print_r($result);die;
    	//-- end doing payment
         if($result->errorcode == '000') {         	
    	  $user  = JFactory::getUser();
    	  
          $post['user_id'] = $user->get('id');
    	
          $obj_customer->bind($post);
          $obj_customer->store();
          
          $post['expiration'] = $post['exp_month'].'/'.$post['exp_year'];
          $obj_payment->bind($post);
          $obj_payment->store();
          
          $post['customer_id'] = $obj_customer->id;
          $post['payment_method_id'] = $obj_payment->id;
          
          $config =& JFactory::getConfig();
		  $tzoffset = $config->getValue('config.offset');
		  $date =& JFactory::getDate(NULL, $tzoffset);
		  $post['order_date'] = $date->toMySQL();
          
          $post['total_price'] = substr($post['total_price'],1);
          
          //-- begin get coupon
          $query = ' SELECT value '
            . ' FROM #__a_coupons '

          ;
          $db->setQuery( $query);
          $post['coupon_value'] = $db->loadResult();
          //-- end get coupon
           //-- begin get server name
          $query = ' SELECT server_name '
            . ' FROM #__a_servers '
			. ' WHERE id = '.$post['server_id']
          ;
          $db->setQuery( $query);
          $post['server_name'] = $db->loadResult();
          //-- end get server name
                    
          $obj_order->bind($post);
          $obj_order->store();
          
          //-- begin send mail to admin and customer
/*          $name		= JRequest::getVar( 'first_name',			'',	'post' ).' '.JRequest::getVar( 'last_name',			'',	'post' );
		  $email	= JRequest::getVar( 'email',		'',			'post' );		
		 
		
		  $subject	= 'Order information - Instantvoiceonline';
		  $body = "Thanks for your order. This is server that you ordered\n
		  		   Name: ".$post['server_name']." \n
		  		   Total price: $".($post['total_price']-$post['coupon_value'])."\n\n\n
		  		   Best regards,
		  		   Instant Voice Online
		  ";
				
		  jimport('joomla.mail.helper');
		  $mail = JFactory::getMailer();

		  $config = JFactory::getConfig()->toArray();
		
		  $mail->addRecipient( $config['mailfrom'],$email );
		  $mail->setSender( array( $email, $name ) );
		  $mail->setSubject( $subject );
		  $mail->setBody( $body );

		  $sent = $mail->Send();
*/		  
          //-- end send mail to admin and customer
		   $this->send_invoice($user->get('email'),$order_id,$user->get('id'));
           $link = JRoute::_('index.php?option=com_servers&view=servers&layout=response');
		   $this->setRedirect($link, $msg);
		   
         }
         else{
         	$link = 'index.php?option=com_servers&layout=product_detail&id='.$post['server_id'].'&cateid='.$get['cateid'];
            $this->setRedirect($link, $result->errormessage);
            return;
         }
    }


    function send_invoice($customer_mail,$order_id,$user_id) {
        require_once(JPATH_SITE."/components/com_servers/views/servers/view.html.php");
        $mailer =& JFactory::getMailer();
        $config =& JFactory::getConfig();
        $sender = array(
            $config->getValue( 'config.mailfrom' ),
            $config->getValue( 'config.fromname' ) );

        $mailer->setSender($sender);
        $customer_mail = array( $sender, $customer_mail);
        //$recipient = array( 'person1@domain.com', 'person2@domain.com', 'person3@domain.com' );
        $mailer->addRecipient($customer_mail);
        $mailbody = new ServersViewServers;
        //$mailbody->send_mail($order_id,$user_id);
        $db =& JFactory::getDBO();
        $query = ' SELECT DISTINCT orders.id as order_id,orders.order_date,orders.total_price,orders.coupon_value,servers.*,customers.*,payment.*'
                .' FROM #__a_orders AS orders '
                .' INNER JOIN `#__a_payment_method` AS payment on payment.id = orders.payment_method_id'
                .' INNER JOIN `#__a_customer` AS customers on customers.id = orders.customer_id'
                .' INNER JOIN `#__a_servers` AS servers on servers.id = orders.server_id'
               // .' INNER JOIN `#__mag_dowload` AS download on download.product_id = product.id'
//                . ' WHERE orders.user_id = '.$user_id
                . ' WHERE orders.order_id = '.$order_id
        ;

        $db->setQuery($query);
        $order_info = $db->loadAssoc();
        
        $body   = $mailbody->send_mail($order_id,$user_id);        
        
        $extension = substr($order_info['image'], strlen($order_info['image'])-3,3);
        $extension = 'image/'.$extension;
        $mailer->isHTML(true);        
        
        $mailer->setBody($body);
        $mailer->setSubject('Instance Servers Online');
        // Optionally add embedded image
        $mailer->AddEmbeddedImage( JPATH_SITE.DS.'images'.DS.'rokquickcart'.DS.$order_info['image'], 'base64', 'phoca_thumb_m_'.$order_info['image'] );
        $send =& $mailer->Send();
        //echo JPATH_SITE.DS.'images'.DS.'magazines'.DS.'thumbs'.DS.'phoca_thumb_m_'.$order_info['image'];
        //var_dump($body);
        //die;
        if ( $send !== true ) {
            echo 'Error sending email: ' . $send->message;
        } else {
            echo 'Mail sent';
        }


    }

    function save_user() {
        global $mainframe;
        // Check for request forgeries
        JRequest::checkToken() or jexit( 'Invalid Token' );

        $option = JRequest::getCmd( 'option');

        // Initialize some variables
        $db			= & JFactory::getDBO();
        $me			= & JUser::getInstance( 62 );
        $acl			=& JFactory::getACL();
        $MailFrom	= $mainframe->getCfg('mailfrom');
        $FromName	= $mainframe->getCfg('fromname');
        $SiteName	= $mainframe->getCfg('sitename');

        // Create a new JUser object
        $user = new JUser(JRequest::getVar( 'id', 0, 'post', 'int'));
        $original_gid = $user->get('gid');

        $post = JRequest::get('post');
        $post['username']	= JRequest::getVar('username', '', 'post', 'username');
        $post['password']	= JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $post['password2']	= JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);

        if (!$user->bind($post)) {
            $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
            $mainframe->enqueueMessage($user->getError(), 'error');
            //$mainframe->redirect( 'index.php?option=com_users', $user->getError() );
            return false;
            //return $this->execute('edit_rep');
        }

        $objectID 	= $acl->get_object_id( 'users', $user->get('id'), 'ARO' );
        $groups 	= $acl->get_object_groups( $objectID, 'ARO' );
        $this_group = strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );


        if ( $user->get('id') == $me->get( 'id' ) && $user->get('block') == 1 ) {
            $msg = JText::_( 'You cannot block Yourself!' );
            $mainframe->enqueueMessage($msg, 'message');
            return $this->execute('edit');
        }
        else if ( ( $this_group == 'super administrator' ) && $user->get('block') == 1 ) {
                $msg = JText::_( 'You cannot block a Super Administrator' );
                $mainframe->enqueueMessage($msg, 'message');
                return $this->execute('edit');
            }
            else if ( ( $this_group == 'administrator' ) && ( $me->get( 'gid' ) == 24 ) && $user->get('block') == 1 ) {
                    $msg = JText::_( 'WARNBLOCK' );
                    $mainframe->enqueueMessage($msg, 'message');
                    return $this->execute('edit');
                }
                else if ( ( $this_group == 'super administrator' ) && ( $me->get( 'gid' ) != 25 ) ) {
                        $msg = JText::_( 'You cannot edit a super administrator account' );
                        $mainframe->enqueueMessage($msg, 'message');
                        return $this->execute('edit');
                    }
        // Are we dealing with a new user which we need to create?
        $isNew 	= ($user->get('id') < 1);
        $userpost    = JRequest::get('post');




        if (!$isNew) {
        // if group has been changed and where original group was a Super Admin
            if ( $user->get('gid') != $original_gid && $original_gid == 25 ) {
            // count number of active super admins
                $query = 'SELECT COUNT( id )'
                    . ' FROM #__users'
                    . ' WHERE gid = 25'
                    . ' AND block = 0'
                ;
                $db->setQuery( $query );
                $count = $db->loadResult();

                if ( $count <= 1 ) {
                // disallow change if only one Super Admin exists
                    $this->setRedirect( 'index.php?option=com_users', JText::_('WARN_ONLY_SUPER') );
                    return false;
                }
            }
            $userpost    = JRequest::get('post');
            $birthday = explode('/',$userpost['birthday']);
            $birthday = mktime(0, 0, 0, $birthday[1], $birthday[0], $birthday[2]);

            $query ="UPDATE #__employee "
                ." SET `address` = '".$userpost["address"]."', `birth_date` = '".$birthday."',"
                ."`phone` = '".$userpost["phone"]."', `region` = '".$userpost["region"]."',"
                ."`country` = '".$userpost["country"]."',"
                ."`postal_code` = '".$userpost["postal_code"]."', `city` = '".$userpost["city"]."'"
                ." WHERE `id` = ".$user->get('id');

            $db->setQuery($query);
            if (!$db->query()) {
                echo JError::raiseError( 500, $db->stderr() );

            }



        }

		/*
	 	 * Lets save the JUser object
	 	 */


        if (!$user->save()) {

            $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');

            switch ($user->getError()) {
                case 'WARNREG_MAIL':
                    $mainframe->enqueueMessage('Please enter a valid e-mail address.', 'error');
                    break;
                case 'WARNREG_INUSE':
                    $mainframe->enqueueMessage('User name already exits.', 'error');
                    break;
                case 'WARNREG_EMAIL_INUSE':
                    $mainframe->enqueueMessage('Email already exits.', 'error');
                    break;
                default:
                    $mainframe->enqueueMessage($user->getError(), 'error');
                    break;
            }

            return $this->execute('edit');
        }



		/*
	 	 * Time for the email magic so get ready to sprinkle the magic dust...
	 	 */
        if ($isNew) {
            $query = 'SELECT MAX(id)'
                . ' FROM #__users'

            ;
            $db->setQuery( $query );
            $lastuserid = $db->loadResult();
            $userpost    = JRequest::get('post');




            $birthday = explode('/',$userpost['birthday']);
            $birthday = mktime(0, 0, 0, $birthday[1], $birthday[0], $birthday[2]);

            $query = 'INSERT INTO #__employee ' .
                '(`id`,  `region`, `birth_date`, `phone`, `address`, `city`, `postal_code`,`country`)'.
                ' VALUES ( '.$lastuserid.', "'.$userpost["region"].'","'.$birthday.'","'. $userpost["phone"].'","'
                .$userpost["address"].'","'. $userpost["city"].'","'. $userpost["postal_code"].'","'. $userpost["country"].'")';
            //echo $query;
            $db->setQuery($query);
            if (!$db->query()) {
                echo JError::raiseError( 500, $db->stderr() );

            }

            $adminEmail = $me->get('email');
            $adminName	= $me->get('name');
            $newuser_message = 'Hello %s,
                                You have been added as a User to %s by an Administrator.
                                This e-mail contains your username and password to log in to %s
                                Username: %s
                                Password: %s
                                Please do not respond to this message as it is automatically generated and is for information purposes only.';
            $subject = 'New user detail';
            $message = sprintf ( $newuser_message, $user->get('name'), $SiteName, JURI::root(), $user->get('username'), $user->password_clear );

            if ($MailFrom != '' && $FromName != '') {
                $adminName 	= $FromName;
                $adminEmail = $MailFrom;
            }
            JUtility::sendMail( $adminEmail, $adminName, $user->get('email'), $subject, $message );
        }

        // If updating self, load the new user object into the session
        if ($user->get('id') == $me->get('id')) {
        // Get an ACL object
            $acl = &JFactory::getACL();

            // Get the user group from the ACL
            $grp = $acl->getAroGroup($user->get('id'));

            // Mark the user as logged in
            $user->set('guest', 0);
            $user->set('aid', 1);

            // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
            if ($acl->is_group_child_of($grp->name, 'Registered')      ||
                $acl->is_group_child_of($grp->name, 'Public Backend')) {
                $user->set('aid', 2);
            }

            // Set the usertype based on the ACL group name
            $user->set('usertype', $grp->name);

            $session = &JFactory::getSession();
            $session->set('user', $user);
        }

        switch ( $this->getTask() ) {

            case 'save':
            default:
                $msg = JText::sprintf( 'Successfully register User', $user->get('name') );
                $this->setRedirect( 'index.php', $msg );
                break;
        }

    }

}
?>
